package org.vison.wonfu.framework.soa.discovery.LoadBalanceImpl;

import org.vison.wonfu.framework.soa.annotation.LoadBalance;
import org.vison.wonfu.framework.soa.discovery.LoadBalanceAlgorithm;
import org.vison.wonfu.framework.soa.discovery.ServiceInstance;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinAlgorithm  implements LoadBalanceAlgorithm {
    private  List<ServiceInstance> serviceInstances;

    public void setServiceInstances(List<ServiceInstance> serviceInstances) {
        this.serviceInstances = serviceInstances;
    }

    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceInstance select() {
        int index = currentIndex.getAndIncrement() % serviceInstances.size();
        if (index < 0) {
            index += serviceInstances.size();
        }
        return serviceInstances.get(index);
    }

    @Override
    public LoadBalance getType() {
        return LoadBalance.ROUND_ROBIN;
    }
}
